package com.xybean;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.servlet.ServletConfig;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.xybean.dao.DAO;
import com.xybean.bean.Product;
import com.xybean.bean.Seller;
import com.xybean.bean.User;

//web.xml
//<servlet-mapping>
//<servlet-name>fileManager</servlet-name>
//<url-pattern>/index.php</url-pattern>
//</servlet-mapping>
public class FileManager extends HttpServlet {
	private static final boolean DEBUG = false;
	private HttpServletRequest request = null;
	private String uploadPath = null;
	private String tmpFileName = "";
	private String tmpFolder = "";
	private static int BUFSIZE = 1024 * 8;

	private Integer productid;
	private String userPicPath = null;
	private String tempPath = null;
	private java.util.Hashtable paramHt = new java.util.Hashtable();
	private ArrayList updFileArr = new ArrayList();

	public void init(ServletConfig cfg) {
		userPicPath = cfg.getServletContext().getRealPath("/upload/") + "/";
		tempPath = cfg.getServletContext().getRealPath("/upload/") + "/tmp/";
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		Enumeration enu = request.getAttributeNames();
		System.out.println(enu.hasMoreElements());
		System.out.println(request.getQueryString());
		System.out.println(request.getRequestURL().toString());
		this.request = request;
		uploadPath = tempPath;
		PrintWriter out = null;
		try {
			out = response.getWriter();
			System.out.println(out.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (request.getParameter("a").equals("uploadavatar")) {
			System.out.println("处理结果："+preSaveImg(out));
		} else if (request.getParameter("a").equals("rectavatar")) {
			saveImg(request, response);
		} else {
			System.out.println(".......................");
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("图片处理");
		// 获取产品ID
		Integer id = (Integer) request.getSession().getAttribute("productid");
		if (id != null) {
			productid = id;
			System.out.println("产品id：" + id);
		}
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":"
		+ request.getServerPort() + path + "/";
		tmpFolder = basePath + "upload/tmp/";
		System.out.println(tmpFolder);
		doGet(request, response);
	}

	/**
	 * ����flash�������
	 * 
	 * @param str
	 * @return
	 */
	public String flashDataDecode(String str) {
		if (null == str)
			return null;
		str = str.trim();
		String ret = "";
		for (int i = 0, j = str.length(); i < j; i = i + 2) {
			int num1 = (int) str.charAt(i) - 48;
			num1 -= num1 > 9 ? 7 : 0;
			int num2 = (int) str.charAt(i + 1) - 48;
			num2 -= num2 > 9 ? 7 : 0;
			ret += (char) (num1 << 4 | num2);
		}
		System.out.println("flash数据:" + ret);
		return ret;
	}

	/**
	 * ����flash�������
	 * 
	 * @param str
	 * @return
	 */
	public byte[] decode(String dataStr) {
		if ((dataStr.length() & 0x01) == 0x01)
			dataStr = new String(dataStr + "0");
		BigInteger cI = new BigInteger(dataStr, 16);
		byte[] data = cI.toByteArray();
		return data;
	}

	/**
	 * ����ͼƬ
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public int saveImg(HttpServletRequest request, HttpServletResponse response) {
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.printf("%09d", 123);
		out.print("r=1");
		response.setContentType("Content-type:application/xml; charset=utf-8");
		response.setHeader("Expires", "0");
		response.setHeader("Cache-Control: private, post-check=0, pre-check=0, max-age=0", "FALSE");
		int status = 0;
		status = preCheck();
		if (DEBUG) {
			Enumeration enu = request.getHeaderNames();
			while (enu.hasMoreElements()) {
				String name = enu.nextElement().toString();
				System.out.println(name + ":" + request.getHeader(name));
			}
		}
		try {

			// 判断商家或会员====或是产品===========================================
			HttpSession s = request.getSession();
			if ((User) s.getAttribute(SessionKey.USER) != null
					|| (Seller) s.getAttribute(SessionKey.SELLER) != null) {
				String realpath = "";
				boolean flat = false;
				if (productid != null) {
					Seller u = (Seller) s.getAttribute(SessionKey.SELLER);
					realpath = userPicPath + "images_tickets/" + u.getUsername() + productid;
				} else if ((User) s.getAttribute(SessionKey.USER) != null) {
					User u = (User) s.getAttribute(SessionKey.USER);
					realpath = userPicPath + "images_users/" + u.getUsername();
					flat = true;
				} else if ((Seller) s.getAttribute(SessionKey.SELLER) != null) {
					Seller u = (Seller) s.getAttribute(SessionKey.SELLER);
					realpath = userPicPath + "images_shops/" + u.getUsername();
				}
				File f = new File(realpath + "1.jpg");
				// FileWriter fw=new FileWriter(
				// f);
				// String f1=flashDataDecode(request.getParameter("avatar1"));
				// fw.write(f1);
				// fw.flush();
				// fw.close();
				// f.setWritable(true);
				FileOutputStream fos = new FileOutputStream(f);
				byte[] bs = decode(request.getParameter("avatar1"));
				fos.write(bs, 1, bs.length - 1);
				fos.flush();
				fos.close();
				// ---
				f = new File(realpath + "2.jpg");
				fos = new FileOutputStream(f);
				bs = decode(request.getParameter("avatar2"));
				fos.write(bs, 1, bs.length - 1);
				fos.flush();
				fos.close();
				// --
				f = new File(realpath + "3.jpg");
				fos = new FileOutputStream(f);
				bs = decode(request.getParameter("avatar3"));
				fos.write(bs, 1, bs.length - 1);
				fos.flush();
				fos.close();
				// 保存到数据库
				ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(request
						.getSession().getServletContext());
				if (flat) {
					DAO<User> userDao = (DAO<User>) ac.getBean("userDao");
					User u = (User) s.getAttribute(SessionKey.USER);
					u = userDao.get(u.getId());
					String tmpurl = "upload/images_users/" + u.getUsername() + "2.jpg";
					String tmpurl3 = "upload/images_users/" + u.getUsername() + "3.jpg";
					u.setPhoto(tmpurl);
					u.setSmallPhoto(tmpurl3);
					userDao.update(u);
					System.out.println("保存成功:" + tmpurl);
				} else {
					if (productid != null) {
						// 产品图标
						DAO<Product> productDao = (DAO<Product>) ac.getBean("productDao");
						Product p = productDao.get(productid);
						Seller u = (Seller) s.getAttribute(SessionKey.SELLER);
						String tmpurl = "upload/images_tickets/" + u.getUsername() + productid + "2.jpg";
						String tmpurl2 = "upload/images_tickets/" + u.getUsername() + productid + "3.jpg";
						p.setPhoto1(tmpurl);
						p.setPhoto2(tmpurl2);
						productDao.update(p);
						System.out.println("保存成功:" + tmpurl);
					} else if (productid == null) {
						DAO<Seller> shopDao = (DAO<Seller>) ac.getBean("shopDao");
						Seller u = (Seller) s.getAttribute(SessionKey.SELLER);
						u = shopDao.get(u.getId());
						String tmpurl = "upload/images_shops/" + u.getUsername() + "2.jpg";
						String tmpurl2 = "upload/images_shops/" + u.getUsername() + "1.jpg";
						String tmpurl3 = "upload/images_shops/" + u.getUsername() + "3.jpg";
						//u.setPhotoA(tmpurl2);
						u.setPhoto(tmpurl);
						u.setSmallPhoto(tmpurl3);
						shopDao.update(u);
						System.out.println("保存成功:" + tmpurl);
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// �ϴ��ɹ���ת�ĵ�ַ
			// request.getRequestDispatcher(forwardPath).forward(request, response);
			out.println("<?xml version=\"1.0\" ?><root><face r=\"1\"/></root>");
			out.println("r=1");
			productid = null;
			// //销毁productid
			// System.out.println("保存成功，销毁productid");
			// request.getSession().removeAttribute("productid");
		}

		return status;
	}

	/**
	 * ������ʱͼƬ
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public int preSaveImg(PrintWriter out) {
		int status = 0;

		status = preCheck();

		if (status != 0)
			return status;
		try {
			System.out.println("图片预览处理");
			String name = null;
			String value = null;
			boolean fileFlag = false;
			File tmpFile = null;
			String fName = null;
			FileOutputStream baos = null;
			BufferedOutputStream bos = null;
			paramHt = new Hashtable();
			updFileArr = new ArrayList();
			int rtnPos = 0;
			byte[] buffs = new byte[BUFSIZE * 8];
			String contentType = request.getContentType();
			int index = contentType.indexOf("boundary=");
			String boundary = "--" + contentType.substring(index + 9);
			String endBoundary = boundary + "--";
			ServletInputStream sis = request.getInputStream();
			while ((rtnPos = sis.readLine(buffs, 0, buffs.length)) != -1) {
				String strBuff = new String(buffs, 0, rtnPos);
				if (strBuff.startsWith(boundary)) {
					if (name != null && name.trim().length() > 0) {
						if (fileFlag) {
							bos.flush();
							baos.close();
							bos.close();
							baos = null;
							bos = null;
							updFileArr.add(fName);
						} else {
							Object obj = paramHt.get(name);
							ArrayList al = new ArrayList();
							if (obj != null) {
								al = (ArrayList) obj;
							}
							al.add(value);
							System.out.println(value);
							paramHt.put(name, al);
						}
					}
					name = new String();
					value = new String();
					fileFlag = false;
					fName = new String();
					rtnPos = sis.readLine(buffs, 0, buffs.length);
					if (rtnPos != -1) {
						strBuff = new String(buffs, 0, rtnPos);
						if (strBuff.toLowerCase().startsWith("content-disposition: form-data; ")) {
							int nIndex = strBuff.toLowerCase().indexOf("name=\"");
							int nLastIndex = strBuff.toLowerCase().indexOf("\"", nIndex + 6);
							name = strBuff.substring(nIndex + 6, nLastIndex);
						}
						int fIndex = strBuff.toLowerCase().indexOf("filename=\"");
						if (fIndex != -1) {
							fileFlag = true;
							int fLastIndex = strBuff.toLowerCase().indexOf("\"", fIndex + 10);
							fName = strBuff.substring(fIndex + 10, fLastIndex);
							fName = getFileName(fName);
							if (fName == null || fName.trim().length() == 0) {
								fileFlag = false;
								sis.readLine(buffs, 0, buffs.length);
								sis.readLine(buffs, 0, buffs.length);
								sis.readLine(buffs, 0, buffs.length);
								continue;
							} else {
								fName = getFileNameByTime(fName);
								sis.readLine(buffs, 0, buffs.length);
								sis.readLine(buffs, 0, buffs.length);
							}
						}
					}
				} else if (strBuff.startsWith(endBoundary)) {
					if (name != null && name.trim().length() > 0) {
						if (fileFlag) {
							bos.flush();
							baos.close();
							bos.close();
							baos = null;
							bos = null;
							updFileArr.add(fName);
						} else {
							Object obj = paramHt.get(name);
							ArrayList al = new ArrayList();
							if (obj != null) {
								al = (ArrayList) obj;
							}
							al.add(value);
							paramHt.put(name, al);
						}
					}
				} else {
					if (fileFlag) {
						if (baos == null && bos == null) {
							tmpFile = new File(uploadPath + fName);
							baos = new FileOutputStream(tmpFile);
							bos = new BufferedOutputStream(baos);
						}
						bos.write(buffs, 0, rtnPos);
						baos.flush();
					} else {
						System.out.println("ifree :" + value + "--" + strBuff);
						value = value + strBuff;
					}
				}
			}
			System.out.println("处理结束--------");
			tmpFileName = tmpFolder + tmpFile.getName();
			out.printf(tmpFileName);// ��Ӧflash
		} catch (IOException e) {
			status = 4;
		} catch (NullPointerException ne) {
			System.out.println(ne.getMessage());
		}

		return status;
	}

	private int preCheck() {
		if (DEBUG) {
			System.out.println(request.getQueryString());
		}
		int errCode = 0;
		if (request == null)
			return 1;
		if (uploadPath == null || uploadPath.trim().length() == 0){
			System.out.println("uploadPath为空");
			return 2;}
		else {
			File tmpF = new File(uploadPath);
			if (!tmpF.exists()){
				System.out.println(uploadPath);
				System.out.println("tmpF.exists:"+tmpF.exists());				
				return 2;
			}
		}
		String contentType = request.getContentType();

		if (contentType.indexOf("multipart/form-data") == -1
				&& contentType.indexOf("application/x-www-form-urlencoded") == -1) {
			return 3;
		}
		return errCode;
	}

	public String getParameter(String name) {
		String value = "";
		if (name == null || name.trim().length() == 0)
			return value;
		value = (paramHt.get(name) == null) ? "" : (String) ((ArrayList) paramHt.get(name)).get(0);
		return value;
	}

	public String[] getParameters(String name) {
		if (name == null || name.trim().length() == 0)
			return null;
		if (paramHt.get(name) == null)
			return null;
		ArrayList al = (ArrayList) paramHt.get(name);
		String[] strArr = new String[al.size()];
		for (int i = 0; i < al.size(); i++)
			strArr[i] = (String) al.get(i);
		return strArr;
	}

	public int getUpdFileSize() {
		return updFileArr.size();
	}

	public String[] getUpdFileNames() {
		String[] strArr = new String[updFileArr.size()];
		for (int i = 0; i < updFileArr.size(); i++)
			strArr[i] = (String) updFileArr.get(i);
		return strArr;
	}

	private String getFileName(String input) {
		int fIndex = input.lastIndexOf("\\");
		if (fIndex == -1) {
			fIndex = input.lastIndexOf("/");
			if (fIndex == -1) {
				return input;
			}
		}
		input = input.substring(fIndex + 1);
		return input;
	}

	private String getFileNameByTime(String input) {
		int index = input.indexOf(".");
		Date dt = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return input.substring(0, index) + sdf.format(dt) + input.substring(index);
	}
}
